<!---总览数据页面-->
<template>
  <div class="ele-body ele-body-card">
    <a-row>
      <a-col :span="12" class="block-space-right">
        <a-card title="设备信息" class="card-width">
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="牛舍名称">{{data.oxtallName}}</a-descriptions-item>
            <a-descriptions-item label="区域名称">{{data.areaName}}</a-descriptions-item>
            <a-descriptions-item label="三相电开关ID">{{data.recordId}}</a-descriptions-item>
            <a-descriptions-item label="设备号">{{data.recordNo}}</a-descriptions-item>
            <a-descriptions-item label="合闸状态">
              <a-tag v-if="threephaseInfo.outputStatus == 1" color="green">合闸</a-tag>
              <a-tag v-else color="red">分闸</a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
      <a-col :span="12" class="block-space-right">
        <!-- 右边统计快 -->
        <a-card title="实时数据" class="card-width">
          <a-row :gutter="8">
            <a-col :span="12">
              <a-card>
                <a-statistic
                  title="分相电能A(KWH)"
                  :value="threephaseInfo.aenergy"
                  :precision="1"
                  suffix=""
                  class="demo-class"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card>
                <a-statistic
                  title="分相电能B(KWH)"
                  :value="threephaseInfo.benergy"
                  :precision="1"
                  suffix=""
                  class="demo-class"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
          </a-row>
          <a-row :gutter="8">
            <a-col :span="12">
              <a-card>
                <a-statistic
                  title="分相电能C(KWH)"
                  :value="threephaseInfo.cenergy"
                  :precision="1"
                  suffix=""
                  class="demo-class"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
            <a-col :span="12">
              <a-card>
                <a-statistic
                  title="分相电能总(KWH)"
                  :value="threephaseInfo.energy"
                  :precision="1"
                  suffix=""
                  class="demo-class"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>

    <!-- 报表统计 -->
    <a-row :gutter="16">
      <a-col :lg="12" :md="14" :sm="24" :xs="24">
        <a-card
          :bordered="false"
          title="总有功功率的对比"
          :body-style="{padding: '16px 6px 0 0'}">
          <template #extra>
            <a-space size="middle" class="analysis-tabs-extra">
              <a-radio-group v-model:value="chartWhere.dateType" @change="selectDataType">
                <a-radio-button :value="1">日环比</a-radio-button>
                <a-radio-button :value="2">周环比</a-radio-button>
                <a-radio-button :value="3">月环比</a-radio-button>
              </a-radio-group>
            </a-space>
          </template>
          <v-chart
            ref="temperatureHumidityChart"
            style="height: 362px;"
            :option="temperatureHumidityChartOption"/>
        </a-card>
      </a-col>
      <a-col :lg="12" :md="10" :sm="24" :xs="24">
        <a-card
          :bordered="false"
          title="最近7天用电量情况"
          :body-style="{padding: '16px 6px 0 0'}">
          <v-chart
            ref="ch4Chart"
            style="height: 362px;"
            :option="methaneChartOption"/>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import { provide } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart, BarChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import VChart, { THEME_KEY } from 'vue-echarts';
import 'echarts-wordcloud';
import { ChartTheme } from 'ele-admin-pro';
import { DeviceLuoxunThreephaseApi } from '@/api/property/DeviceLuoxunThreephaseApi';
import moment from 'moment'
import axios from 'axios';
import {DeviceLuoxunThreephaseDataApi} from "@/api/property/DeviceLuoxunThreephaseDataApi";
import {DeviceLuoxunThreephaseDateApi} from "@/api/property/DeviceLuoxunThreephaseDateApi";

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
]);

provide(THEME_KEY, ChartTheme);

export default {
  name: 'DeviceLuoxunThreephaseMonitor',
  components: {
    VChart,
  },
  props: {
    data: Object
  },
  data() {
    return {
      // 最近1小时温度情况
      powerDataLast : [],
      powerDataCurrent : [],
      powerLegendData : [
        moment().subtract(1, 'days').format('YYYYMMDD'),
        moment().format('YYYYMMDD')
      ],
      enegyDateData: [], //日均消费
      threephaseInfo : {},
      loadTimer:null, //定义一个刷新的timer
      loadDetailTimer : null,
      chartWhere : {
        "dateType" : 1
      }
    };
  },
  mounted() {
    this.getPhaseData();
    this.getEnegyData();
    this.getDetail();
    this.loadTimer = setInterval(this.getPhaseData, 30000);
    this.loadDetailTimer = setInterval(this.getDetail, 30000);
  },
  beforeUnmount() {
    clearInterval(this.loadTimer);
    clearInterval(this.loadDetailTimer);
  },
  computed: {
    //甲烷
    methaneChartOption(){
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['分相A用电量(KWH)', '分相B用电量(KWH)', '分相C用电量(KWH)', '分相总用电量(KWH)'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.enegyDateData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '分相A用电量(KWH)',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {
              opacity: 0.5
            },
            data: this.enegyDateData.map(d => d.aenergyTotal)
          },
          {
            name: '分相B用电量(KWH)',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {
              opacity: 0.5
            },
            data: this.enegyDateData.map(d => d.benergyTotal)
          },
          {
            name: '分相C用电量(KWH)',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {
              opacity: 0.5
            },
            data: this.enegyDateData.map(d => d.cenergyTotal)
          },
          {
            name: '分相总用电量(KWH)',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {
              opacity: 0.5
            },
            data: this.enegyDateData.map(d => d.energyTotal)
          }
        ]
      }
    },
    // 最近1小时温度情况折线图配置
    temperatureHumidityChartOption() {
      /*if (!this.visitHourData.length) {
        return null;
      }*/
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.powerLegendData,
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.powerDataCurrent.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: this.powerLegendData[0],
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {
              opacity: 0.5
            },
            data: this.powerDataLast.map(d => d.activitypower)
          },
          {
            name: this.powerLegendData[1],
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {
              opacity: 0.5
            },
            data: this.powerDataCurrent.map(d => d.activitypower)
          }
        ]
      }
    }
  },
  methods: {
    getDetail() {
      let that = this;
      DeviceLuoxunThreephaseApi.detailByRecord(this.data.recordId).then(result => {
        that.threephaseInfo = result || {};
      });
    },
    selectDataType () {
      clearInterval(this.loadTimer);
      this.getPhaseData();
      this.loadTimer = setInterval(this.getPhaseData, 30000);
    },
    getEnegyData() { //获取用电量
      let params = {
        searchBeginTime : moment().subtract(7, 'days').format('YYYY-MM-DD'),
        searchEndTime : moment().format('YYYY-MM-DD'),
        recordId : this.data.recordId,
        orderBy : "asc",
        sortBy : "pltd_date"
      };
      DeviceLuoxunThreephaseDateApi.list(params).then(res => {
          let _engryDateData = [];
          if (res && res.length > 0) {
            res.forEach(function(item) {
              let formatItem = {
                time : item.pltdDate,
                aenergyTotal : item.aenergyTotal,
                benergyTotal : item.benergyTotal,
                cenergyTotal : item.cenergyTotal,
                energyTotal : item.energyTotal
              };
              _engryDateData.push(formatItem);
            });
          } else {
            _engryDateData.push({
              time : moment().subtract(2, 'days').format('YYYYMMDD'),
              aenergyTotal : 0,
              benergyTotal : 0,
              cenergyTotal : 0,
              energyTotal : 0
            });
            _engryDateData.push({
              time : moment().format('YYYYMMDD'),
              aenergyTotal : 0,
              benergyTotal : 0,
              cenergyTotal : 0,
              energyTotal : 0
            });
          }
          this.enegyDateData = _engryDateData;
      });
    },
    getPhaseData() {
      let lastSearchBeginTime = '';
      let lastSearchEndTime = '';
      let searchBeginTime = '';
      let searchEndTime = '';
      if (this.chartWhere.dateType == 2) { //周同比
        searchBeginTime = moment().format('YYYY-MM-DD 00:00:00');
        searchEndTime = moment().format('YYYY-MM-DD HH:mm:ss');
        lastSearchBeginTime = moment(searchBeginTime).subtract(7, 'days').format('YYYY-MM-DD 00:00:00');
        lastSearchEndTime = moment(searchEndTime).subtract(7, 'days').format('YYYY-MM-DD HH:mm:ss');
        this.powerLegendData = [
          moment(lastSearchBeginTime).format('YYYYMMDD'),
          moment(searchBeginTime).format('YYYYMMDD')
        ];
      } else if (this.chartWhere.dateType == 3) { //月同比
        searchBeginTime = moment().format('YYYY-MM-DD 00:00:00');
        searchEndTime = moment().format('YYYY-MM-DD HH:mm:ss');
        lastSearchBeginTime = moment(searchBeginTime).subtract(30, 'days').format('YYYY-MM-DD 00:00:00');
        lastSearchEndTime = moment(searchEndTime).subtract(30, 'days').format('YYYY-MM-DD HH:mm:ss');
        this.powerLegendData = [
          moment(lastSearchBeginTime).format('YYYYMMDD'),
          moment(searchBeginTime).format('YYYYMMDD')
        ];
      } else {//dataType == 1 //日同比
        searchBeginTime = moment().format('YYYY-MM-DD 00:00:00');
        searchEndTime = moment().format('YYYY-MM-DD HH:mm:ss');
        lastSearchBeginTime = moment(searchBeginTime).subtract(1, 'days').format('YYYY-MM-DD 00:00:00');
        lastSearchEndTime = moment(searchEndTime).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
        this.powerLegendData = [
          moment().subtract(1, 'days').format('YYYYMMDD'),
          moment().format('YYYYMMDD')
        ];
      }
      let lastParams = {
        searchBeginTime :lastSearchBeginTime,
        searchEndTime : lastSearchEndTime,
        recordId : this.data.recordId,
        orderBy : "asc",
        sortBy : "upload_time"
      };
      let params = {
        searchBeginTime :searchBeginTime,
        searchEndTime : searchEndTime,
        recordId : this.data.recordId,
        orderBy : "asc",
        sortBy : "upload_time"
      };
      axios.all([DeviceLuoxunThreephaseDataApi.list(lastParams), DeviceLuoxunThreephaseDataApi.list(params)])
        .then(axios.spread((lastRes, currentRes) => {
            let _powerData = {};
            if (lastRes && lastRes.length > 0) {
              console.log(lastRes);
              lastRes.forEach(function(item) {
                let formatItem = {
                  time : item.uploadTime.substr(11, 5),
                  activitypower : item.activitypower,
                };
                _powerData[formatItem["time"]] = formatItem;
              });
            } else {
              let time1 = moment().subtract(20, 'minute').format('HH:mm');
              _powerData[time1] = {
                time: time1,
                activitypower: 0,
              };
              let time2 = moment().subtract(10, 'minute').format('HH:mm');
              _powerData[time2] = {
                time: time2,
                activitypower: 0,
              };
              let time3 = moment().subtract(5, 'minute').format('HH:mm');
              _powerData[time3] = {
                time: time3,
                activitypower: 0,
              };
            }


            let _currentPowerData = {};
            if (currentRes && currentRes.length > 0) {
              console.log(currentRes);
              currentRes.forEach(function(item) {
                let formatItem = {
                  time : item.uploadTime.substr(11, 5),
                  activitypower : item.activitypower,
                };
                _currentPowerData[formatItem["time"]] = formatItem;
              });
            } else {
              let time4 = moment().subtract(20, 'minute').format('HH:mm');
              _currentPowerData[time4] = {
                time: time4,
                activitypower: 0,
              };
              let time5 = moment().subtract(10, 'minute').format('HH:mm');
              _currentPowerData[time5] = {
                time: time5,
                activitypower: 0,
              };
              let time6 = moment().subtract(5, 'minute').format('HH:mm');
              _currentPowerData[time6] = {
                time: time6,
                activitypower: 0,
              };
            }
            for(var key in _currentPowerData){
              if (_powerData[key] == null) {
                _powerData[key] = {
                  time: key,
                  activitypower : 0
                };
              }
            }

          for(var key1 in _powerData){
            if (_currentPowerData[key1] == null) {
              _currentPowerData[key1] = {
                time: key1,
                activitypower : 0
              };
            }
          }
          this.powerDataCurrent = [];
          for(var key3 in _currentPowerData){
            this.powerDataCurrent.push(_currentPowerData[key3]);
          }
          this.powerDataLast = [];
          for(var key4 in _powerData){
            this.powerDataLast.push(_powerData[key4]);
          }
          console.log(this.powerDataCurrent );
          console.log(this.powerDataLast);
        }));
    }
  },
  activated() {
    ['temperatureHumidityChart', 'ch4Chart'].forEach((name) => {
      this.$refs[name].resize();
    });
  }
};
</script>
<style scoped>
.block-space-top {
  /*上右下左*/
  padding: 10px 0 0 0;
}

.block-space-right {
  padding: 0 5px 0 0;
}

.block-space-left {
  padding: 0 0 0 5px;
}

.card-width {
  width: 100%;
}
@media screen and (max-width: 880px) {
  .analysis-tabs-extra {
    display: none;
  }
}
</style>
